package com.easyboot.web.monitor.jobutils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.NumberUtil;
import com.easyboot.utils.log.LoggerHelper;
import com.easyboot.framework.utils.spring.SpringUtils;
import com.easyboot.web.monitor.domain.MonitorJobLog;
import com.easyboot.web.monitor.service.MonitorJobLogService;
import org.quartz.*;

import java.util.Date;

/**
 * @author yushuo
 * @className
 * @descripton TODO
 * @date 2021/6/23 17:26
 **/
public class EasyQuartzJobListener implements JobListener {

    /**
     * 线程本地变量
     */
    private static ThreadLocal<Date> threadLocal = new ThreadLocal<>();
    @Override
    public String getName() {
        return "job1_to_job2";
    }


    @Override
    public void jobToBeExecuted(JobExecutionContext inContext) {
        threadLocal.set(new Date());
        LoggerHelper.console("Job1Listener says: 作业即将执行.");

    }

    //当org.quartz被调度程序调用时。JobDetailwas即将执行(一个关联的Triggerhas发生)，但是TriggerListener否决了它的执行。
    @Override
    public void jobExecutionVetoed(JobExecutionContext inContext) {
        LoggerHelper.console("Job1Listener says: 作业执行被否决.");
    }

    @Override
    public void jobWasExecuted(JobExecutionContext inContext, JobExecutionException inException) {
        LoggerHelper.console("Job1Listener says: 作业已执行.");
        Date startTime = threadLocal.get();
        threadLocal.remove();
        Date endTime=DateUtil.date();
        long runMs = endTime.getTime() - startTime.getTime();


        JobDataMap dataMap = inContext.getJobDetail().getJobDataMap();
        Long jobId=dataMap.getLong("jobId");
        final MonitorJobLog jobLog=new MonitorJobLog();
        jobLog.setJobId(jobId);
        jobLog.setExcuteTime(startTime);
        jobLog.setExcuteResult(0);
         if(runMs<1000){
             jobLog.setElapsedTime(runMs + "毫秒");
         }else{
            double elapsed=NumberUtil.div(runMs,1000);
             jobLog.setElapsedTime(elapsed + "秒");
         }

        if(inException!=null){
            jobLog.setExcuteResult(1);
            String error=ExceptionUtil.getMessage(inException)+"："+ ExceptionUtil.stacktraceToString(inException,1000);
            jobLog.setErrorMessage(error);

        }
        LoggerHelper.console("this job start at "+ DateUtil.formatDateTime(startTime) +" excute end at:"+ DateUtil.now());
        SpringUtils.getBean(MonitorJobLogService.class).addJobLog(jobLog);
    }
}
